package admin

import (
	"night-school-api/models"
	"night-school-api/utils"
	"night-school-api/database"

	// "fmt"
	"time"
    "sync"
	"github.com/labstack/echo/v4"
)


// 创建一个 sync.Map 作为缓存
var cacheInstance sync.Map

// 定义一个结构体来存储缓存项及其过期时间
type cacheItem struct {
    value     interface{}
    expiration time.Time
}

// 检查缓存项是否过期
func isExpired(item cacheItem) bool {
    return !item.expiration.IsZero() && time.Now().After(item.expiration)
}


func GetStatistic(c echo.Context) error {

	key := "cache_statistic"
	
    // 尝试从缓存中获取数据
    if cached, found := cacheInstance.Load(key); found {
        item := cached.(cacheItem)
        if !isExpired(item) {
			return utils.JSONSuccess(c, item.value, "")
        }
    }

	cacheKey := "cache_statistic"
	rs := utils.CacheGet(cacheKey)

	cacheData, ok := rs.(map[string][]map[string]interface{})
	if ok {
		return utils.JSONSuccess(c, cacheData, "")
	}


    // 如果缓存中没有数据或已过期，模拟从数据源获取数据
	data := make(map[string][]map[string]interface{})
	data["teacher_count"] = make([]map[string]interface{}, 12)
	data["course_count"] = make([]map[string]interface{}, 12)
	data["enrollment_count"] = make([]map[string]interface{}, 12)

	db := database.DB

	var teacherCount int64
	var courseCount int64
	var enrollmentCount int64

    // 一年前
    oneYearAgo := time.Now().AddDate(0, -11, 0)
    // 循环得到最近 12 个月的每个月的时间
    for i := 0; i < 12; i++ {
        // 往后推 i 个月的时间
        month := oneYearAgo.AddDate(0, i, 0)
        // 获取该月的开始时间
        startOfMonth := time.Date(month.Year(), month.Month(), 1, 0, 0, 0, 0, models.TimeLocation)
		// 获取下个月的第一天
		nextMonth := time.Date(month.Year(), month.Month()+1, 1, 0, 0, 0, 0, models.TimeLocation)
		// 下个月的第一天减去一天就是当前月的最后一天
		endOfMonth := nextMonth.AddDate(0, 0, -1)

		yearMonthStr := startOfMonth.Format("2006-01")

        // 打印该月的开始时间
		// fmt.Println("startOfMonth: " + startOfMonth.Format("2006-01-02 15:04:05"))
		// fmt.Println("endOfMonth: " + endOfMonth.Format("2006-01-02 15:04:05"))


		db.Model(&models.Course{}).Distinct("user_id").Where("created_at >= ?", startOfMonth).Where("created_at < ?", endOfMonth).Count(&teacherCount)

		db.Model(&models.Course{}).Where("created_at >= ?", startOfMonth).Where("created_at < ?", endOfMonth).Count(&courseCount)

		db.Model(&models.Enrollment{}).Where("created_at >= ?", startOfMonth).Where("created_at < ?", endOfMonth).Where("status = ?", models.AuditApproved).Count(&enrollmentCount)

		tm := map[string]interface{}{
			"time": yearMonthStr,
			"count": int(teacherCount),
		}
		cm := map[string]interface{}{
			"time": yearMonthStr,
			"count": int(courseCount),
		}
		em := map[string]interface{}{
			"time": yearMonthStr,
			"count": int(enrollmentCount),
		}
		data["teacher_count"][i] = tm
		data["course_count"][i] = cm
		data["enrollment_count"][i] = em
	}


    // 设置缓存过期时间
    expiration := time.Now().Add(5 * 24 * time.Hour)
	utils.CacheSet(cacheKey, data, expiration)

	return utils.JSONSuccess(c, data, "")
}